package org.framework.customutil;

import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.BufferedReader;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.text.DateFormat;  
import java.text.MessageFormat;  
import java.util.ArrayList;  
import java.util.Date;  
import java.util.Enumeration;  
import java.util.List;  
import java.util.Locale;  
import java.util.StringTokenizer;  
import java.util.zip.ZipEntry;  
import java.util.zip.ZipFile;  
   
/**
 * @Title: FileUtil.java .<br>
 * @Package org.framework.customutil .<br>
 * @Description: 文件工具类 .<br>
 * @author 郑成功 .<br>
 * @email a876459952@qq.com .<br>
 * @date 2018-6-20 下午10:21:11.<br>
 * @version V1.0.<br>
 */
public class FileUtil {  
    public static String dirSplit = "\\";//文件分隔符
    /**
     * @Description: 保存文件 .<br>
     * @param physicalPath 保存路径.<br>
     * @param istream 输入流.<br>
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:23:10.<br>
     */
    public static boolean SaveFileByPhysicalDir(String physicalPath,  
            InputStream istream) {  
        boolean flag = false;  
        try {  
            OutputStream os = new FileOutputStream(physicalPath);  
            int readBytes = 0;  
            byte buffer[] = new byte[8192];  
            while ((readBytes = istream.read(buffer, 0, 8192)) != -1) {  
                os.write(buffer, 0, readBytes);  
            }  
            os.close();  
            flag = true;  
        } catch (FileNotFoundException e) {  
              
            e.printStackTrace();  
        } catch (IOException e) {  
          
            e.printStackTrace();  
        }  
        return flag;  
    }  
    
    /**
     * @Description: 创建文件 .<br>
     * @param dir 文件 .<br>
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:25:13.<br>
     */
    public static boolean CreateDirectory(String dir){  
        File f = new File(dir);  
        if (!f.exists()) {  
            f.mkdirs();  
        }  
        return true;  
    }  
      
      
    public static void saveAsFileOutputStream(String physicalPath,String content) {  
          File file = new File(physicalPath);  
          boolean b = file.getParentFile().isDirectory();  
          if(!b){  
              File tem = new File(file.getParent());  
              // tem.getParentFile().setWritable(true);  
              tem.mkdirs();// 创建目录  
          }  
          //Log.info(file.getParent()+";"+file.getParentFile().isDirectory());  
          FileOutputStream foutput =null;  
          try {  
              foutput = new FileOutputStream(physicalPath);  
                
              foutput.write(content.getBytes("UTF-8"));  
              //foutput.write(content.getBytes());  
          }catch(IOException ex) {  
              ex.printStackTrace();  
              throw new RuntimeException(ex);  
          }finally{  
              try {  
                  foutput.flush();  
                  foutput.close();  
              }catch(IOException ex){  
                  ex.printStackTrace();  
                  throw new RuntimeException(ex);  
              }  
          }  
            //Log.info("文件保存成功:"+ physicalPath);  
         }  
      
    /**
     * @Description: 文件拷贝 .<br>
     * @param srcFile 源文件.<br>
     * @param desFile 目标文件.<br>
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:26:03.<br>
     */
    public boolean copyToFile(String srcFile, String desFile) {  
        File scrfile = new File(srcFile);  
        if (scrfile.isFile() == true) {  
            int length;  
            FileInputStream fis = null;  
            try {  
                fis = new FileInputStream(scrfile);  
            }  
            catch (FileNotFoundException ex) {  
                ex.printStackTrace();  
            }  
            File desfile = new File(desFile);  
  
            FileOutputStream fos = null;  
            try {  
                fos = new FileOutputStream(desfile, false);  
            }  
            catch (FileNotFoundException ex) {  
                ex.printStackTrace();  
            }  
            desfile = null;  
            length = (int) scrfile.length();  
            byte[] b = new byte[length];  
            try {  
                fis.read(b);  
                fis.close();  
                fos.write(b);  
                fos.close();  
            }  
            catch (IOException e) {  
                e.printStackTrace();  
            }  
        } else {  
            scrfile = null;  
            return false;  
        }  
        scrfile = null;  
        return true;  
    }  
  
    /**
     * @Description: 文件夹拷贝 .<br>
     * @param sourceDir 源文件夹.<br>
     * @param destDir 目标文件夹.<br>
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:27:00.<br>
     */
    public boolean copyDir(String sourceDir, String destDir) {  
        File sourceFile = new File(sourceDir);  
        String tempSource;  
        String tempDest;  
        String fileName;  
        File[] files = sourceFile.listFiles();  
        for (int i = 0; i < files.length; i++) {  
            fileName = files[i].getName();  
            tempSource = sourceDir + "/" + fileName;  
            tempDest = destDir + "/" + fileName;  
            if (files[i].isFile()) {  
                copyToFile(tempSource, tempDest);  
            } else {  
                copyDir(tempSource, tempDest);  
            }  
        }  
        sourceFile = null;  
        return true;  
    }  
  
    /**
     * @Description: 删除指定目录及其中的所有内容。  .<br>
     * @param dir 要删除的目录  .<br> 
     * @return 删除成功时返回true，否则返回false.<br>   
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:28:01.<br>
     */
    public boolean deleteDirectory(File dir) {  
        File[] entries = dir.listFiles();  
        int sz = entries.length;  
        for (int i = 0; i < sz; i++) {  
            if (entries[i].isDirectory()) {  
                if (!deleteDirectory(entries[i])) {  
                    return false;  
                }  
            } else {  
                if (!entries[i].delete()) {  
                    return false;  
                }  
            }  
        }  
        if (!dir.delete()) {  
            return false;  
        }  
        return true;  
    }  
      
    /**
     * @Description: 检测文件是否存在 .<br>
     * @param sFileName 文件名.<br>
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:31:15.<br>
     */
    public static boolean checkExist(String sFileName) {  
    	boolean result = false;  
    	try {  
    		File f = new File(sFileName);  
	       if (f.exists() && f.isFile()) {  
	            result = true;  
	       } else {  
	            result = false;  
	       }  
       } catch (Exception e) {  
            result = false;  
       }  
        return result;  
    }  
     
    /**
     * @Description: 得到文件大小 .<br>
     * @param sFileName 文件名.<br>
     * @return 返回文件长度，文件不存在时返回-1.<br>   
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:32:44.<br>
     */
    public static long getSize(String sFileName) {  
    	long lSize = 0;  
        try {  
            File f = new File(sFileName);  
            if (f.exists()) {  
                if (f.isFile() && f.canRead()) {  
                	lSize = f.length();  
                } else {  
                	lSize = -1;  
                }  
            } else {  
                lSize = 0;  
            }  
       } catch (Exception e) {  
            lSize = -1;  
       }  
       return lSize;  
    }  
     
    /**
     * @Description: 删除文件 .<br>
     * @param sFileName 文件名 .<br>
     * @return 成功：true.<br>   
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:33:38.<br>
     */
    public static boolean deleteFromName(String sFileName) {  
        boolean bReturn = true;  
        try {  
            File oFile = new File(sFileName);  
           if (oFile.exists()) {  
               boolean bResult = oFile.delete();  
               if (bResult == false) {  
                   bReturn = false;  
               }  
           }
     
      } catch (Exception e) {  
          bReturn = false;  
      }  
      return bReturn;  
    }  
     
    /**
     * @Description: 文件压缩 .<br>
     * @param sToPath 压缩文件路径 .<br>
     * @param sZipFile 压缩后文件.<br>
     * @throws Exception .<br>   
     * @author 郑成功 .<br>
     * @date 2018-6-20 下午10:35:18.<br>
     */
	 @SuppressWarnings("rawtypes")  
	 public static void releaseZip(String sToPath, String sZipFile) throws Exception {  
		 if (null == sToPath ||("").equals(sToPath.trim())) {  
			 File objZipFile = new File(sZipFile);  
			 sToPath = objZipFile.getParent();  
		 }  
		 ZipFile zfile = new ZipFile(sZipFile);  
		 Enumeration zList = zfile.entries();  
		 ZipEntry ze = null;  
		 byte[] buf = new byte[1024];  
		 while (zList.hasMoreElements()) {  
			 ze = (ZipEntry) zList.nextElement();  
			 if (ze.isDirectory()) {  
				 continue;  
			 }  
			 OutputStream os =  new BufferedOutputStream(  
			 new FileOutputStream(getRealFileName(sToPath, ze.getName())));  
			 InputStream is = new BufferedInputStream(zfile.getInputStream(ze));  
			 int readLen = 0;  
			 while ((readLen = is.read(buf, 0, 1024)) != -1) {  
				 os.write(buf, 0, readLen);  
			 }  
			 is.close();  
			 os.close();  
		 }  
		 zfile.close();  
	 }  
   
 /** 
  * getRealFileName 
  * 
  * @param  baseDir   Root Directory 
  * @param  absFileName  absolute Directory File Name 
  * @return java.io.File     Return file 
  */  
 @SuppressWarnings({ "rawtypes", "unchecked" })  
private static File getRealFileName(String baseDir, String absFileName) throws Exception {  
  File ret = null;  
  
  List dirs = new ArrayList();  
  StringTokenizer st = new StringTokenizer(absFileName, System.getProperty("file.separator"));  
  while (st.hasMoreTokens()) {  
      dirs.add(st.nextToken());  
  }  
  
  ret = new File(baseDir);  
  if (dirs.size() > 1) {  
      for (int i = 0; i < dirs.size() - 1; i++) {  
          ret = new File(ret, (String) dirs.get(i));  
      }  
  }  
  if (!ret.exists()) {  
      ret.mkdirs();  
  }  
  ret = new File(ret, (String) dirs.get(dirs.size() - 1));  
  return ret;  
 }  
  
 /** 
  * copyFile 
  * 
  * @param  srcFile   Source File 
  * @param  targetFile   Target file 
  */  
 @SuppressWarnings("resource")  
 static public void copyFile(String srcFile , String targetFile) throws IOException  
  {  
    
   FileInputStream reader = new FileInputStream(srcFile);  
   FileOutputStream writer = new FileOutputStream(targetFile);  
  
   byte[] buffer = new byte [4096];  
   int len;  
  
   try  
   {  
       reader = new FileInputStream(srcFile);  
       writer = new FileOutputStream(targetFile);  
         
       while((len = reader.read(buffer)) > 0)  
       {  
           writer.write(buffer , 0 , len);  
       }  
   }  
   catch(IOException e)  
   {  
       throw e;  
   }  
   finally  
   {  
       if (writer != null)writer.close();  
       if (reader != null)reader.close();  
   }  
  }  
  
 /**
  * @Description: 读取文件到目标文件 .<br>
  * @param srcFile 源文件.<br>
  * @param targetFile 目标文件.<br>
  * @throws IOException .<br>   
  * @author 郑成功 .<br>
  * @date 2018-6-22 上午9:08:55.<br>
  */
  public static void renameFile(String srcFile , String targetFile) throws IOException {  
	  try {  
		  copyFile(srcFile,targetFile);  
		  deleteFromName(srcFile);  
	  } catch(IOException e){  
		  throw e;  
	  }  
  }  
  
 /**
  * @Description: 写入文件 .<br>
  * @param tivoliMsg 写入内容.<br>   
  * @param logFileName 日志文件名.<br>   
  * @author 郑成功 .<br>
  * @date 2018-6-22 上午9:05:13.<br>
  */
 public static void write(String tivoliMsg,String logFileName) {  
	 try{  
		 byte[]  bMsg = tivoliMsg.getBytes();  
		 FileOutputStream fOut = new FileOutputStream(logFileName, true);  
		 fOut.write(bMsg);  
		 fOut.close();  
	 } catch(IOException e){  
		 //throw the exception        
	 }  
 }  
 /** 
 * This method is used to log the messages with timestamp,error code and the method details 
 * @param errorCd String 
 * @param className String 
 * @param methodName String 
 * @param msg String 
 */  
 public static void writeLog(String logFile, String batchId, String exceptionInfo) {  
    
  DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.JAPANESE);  
    
  Object args[] = {df.format(new Date()), batchId, exceptionInfo};  
    
  String fmtMsg = MessageFormat.format("{0} : {1} : {2}", args);  
    
  try {  
     
   File logfile = new File(logFile);  
   if(!logfile.exists()) {  
    logfile.createNewFile();  
   }  
     
      FileWriter fw = new FileWriter(logFile, true);  
      fw.write(fmtMsg);  
      fw.write(System.getProperty("line.separator"));  
  
      fw.flush();  
      fw.close();  
  
  } catch(Exception e) {  
  }  
 }  
 
 /**
  * @Description: 读取文件 .<br>
  * @param realPath 文件真实路径.<br>
  * @throws Exception 抛出异常.<br>   
  * @author 郑成功 .<br>
  * @date 2018-6-22 上午9:06:50.<br>
  */
 public static String readTextFile(String realPath) throws Exception {  
     File file = new File(realPath);  
        if (!file.exists()){  
            System.out.println("File not exist!");  
            return null;  
      }  
      BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(realPath),"UTF-8"));     
      String temp = "";  
      String txt="";  
      while((temp = br.readLine()) != null){  
          txt+=temp;  
       }        
      br.close();  
     return txt;  
 }
 
 /**
  * @Description: 保存文件 .<br>
  * @param filePath 文件路径.<br>
  * @param content 保存的内容 ，file.getBytes().<br>
  * @throws IOException 流异常.<br>   
  * @author 郑成功 .<br>
  * @date 2018-6-22 上午9:06:13.<br>
  */
 public static void saveFile(String filePath, byte[] content) throws IOException {
		BufferedOutputStream bos = null;
		try {
			File file = new File(filePath);
			//判断文件路径是否存在
			if (!file.getParentFile().exists()) {
				//文件路径不存在时，创建保存文件所需要的路径
				file.getParentFile().mkdirs();
			}
			//创建文件（这是个空文件，用来写入上传过来的文件的内容）
			file.createNewFile();
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bos.write(content);
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException("文件不存在。");
		} finally {
			if (null != bos) {
				bos.close();
			}
		}
	}
  
   
}  